<?php
namespace app\admin\model;
use think\Model;
class Cate extends Model
{
    //连表查询获取子孙树
    public function cateTreemodel($_cateRes){
        $cateres=$_cateRes;
        return $this->getTree($cateres);
    }

   public function cateTree()
   {
     $cateres=db('cate')->order('sort asc')->select();
     return $this->getTree($cateres);
   }

   //得到栏目顶级栏目及下子栏目集合递归
   public function getTree($data,$pid=0,$level=0){
      static $tree=array();
      foreach ($data as $k => $v) {
        if($v['pid'] ==$pid){
            $v['level']=$level;
            $tree[]=$v;
            $this->getTree($data,$v['id'],$level+1);
        }
      }
      return $tree;
   }

   //获取当前栏目所有子栏目id
   public function cateChildrenId($cateid){
        $data=$this->field('id,pid')->select();
        $arr=$this->_cateChildrenID($data,$cateid);
        return $arr;
   }

   private function _cateChildrenID($data,$cateid){
         static $arr=array();
         foreach ($data as $k => $v) {
            if($v['pid'] == $cateid){
                $arr[]=$v['id'];
                $this->_cateChildrenID($data,$v['id']);
            }
         }
         return $arr;
   }
   
    //获得当前修改栏目的家谱树
    public function editTree($id){
        static $tree=array();
        $cates=$this->select();

      while ($id>0){
        foreach ($cates as $v) {
          if($v['id']==$id){
            $tree[]=$v;

            $id=$v['pid'];
            break;
          }
        }
      }
      return $tree;
    }
}
